<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <!-- 原有头部代码保持不变 -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能灯控制平台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        /* 原有样式保持不变 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', sans-serif;
        }

        body {
            background-color: #f0f2f5;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        }

        .container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
            padding: 30px;
            width: 100%;
            max-width: 500px;
        }

        .header {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 30px;
        }

        .header-icon {
            font-size: 2.5em;
            color: #1a73e8;
            margin-right: 10px;
        }

        .title {
            color: #1a73e8;
            font-size: 1.8em;
            font-weight: 600;
        }

        .form-card {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 25px;
        }

        .mode-switch {
            display: flex;
            justify-content: center;
            margin-bottom: 25px;
        }

        .mode-btn {
            flex: 1;
            padding: 12px 20px;
            border: none;
            border-radius: 8px;
            font-size: 1em;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #f0f0f0;
            color: #666;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .mode-btn.active {
            background: #1a73e8;
            color: white;
            box-shadow: 0 2px 8px rgba(26, 115, 232, 0.2);
        }

        .mode-btn i {
            font-size: 1.2em;
        }

        .gear-group {
            margin-bottom: 20px;
            display: none;
        }

        .gear-label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }

        .gear-select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 1em;
            background: white;
            appearance: none;
            cursor: pointer;
            transition: border-color 0.3s;
        }

        .gear-select:focus {
            border-color: #1a73e8;
            outline: none;
        }

        .action-btn {
            width: 100%;
            padding: 12px;
            background: #1a73e8;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1em;
            font-weight: 500;
            cursor: pointer;
            transition: transform 0.3s ease;
        }

        .action-btn:hover {
            transform: scale(1.02);
            box-shadow: 0 4px 12px rgba(26, 115, 232, 0.2);
        }

        .feedback-toast {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            border-radius: 10px;
            font-size: 1em;
            color: white;
            opacity: 0;
            transform: translateY(-20px);
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .feedback-toast.show {
            opacity: 1;
            transform: translateY(0);
        }

        .success-toast {
            background: #2e7d32;
            box-shadow: 0 2px 8px rgba(46, 125, 50, 0.2);
        }

        .error-toast {
            background: #b71c1c;
            box-shadow: 0 2px 8px rgba(183, 28, 28, 0.2);
        }

        .sensor-display {
            margin-top: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 12px;
            text-align: center;
        }

        .sensor-item {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }

        .sensor-label {
            font-weight: 500;
            color: #333;
        }

        .sensor-value {
            font-size: 1.1em;
            color: #1a73e8;
        }

        /* 新增开关按钮样式 */
        .switch-container {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin: 25px 0;
        }

        .state-btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            font-size: 1em;
            cursor: pointer;
            transition: background 0.3s ease;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .turn-on-btn {
            background: #2e7d32;
            color: white;
        }

        .turn-on-btn:hover {
            background: #276b2a;
        }

        .turn-off-btn {
            background: #b71c1c;
            color: white;
        }

        .turn-off-btn:hover {
            background: #8e1616;
        }

        .state-btn i {
            font-size: 1.2em;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <i class="fas fa-lightbulb header-icon"></i>
        <div class="title">智能灯控制平台</div>
    </div>

    <div class="form-card">
        <div class="mode-switch">
            <button type="button" class="mode-btn active" data-mode="manual_mode">
                <i class="fas fa-sliders-h"></i> 手动模式
            </button>
            <button type="button" class="mode-btn" data-mode="auto_mode">
                <i class="fas fa-play"></i> 自动模式
            </button>
        </div>

        <div class="gear-group" id="gearGroup">
            <label class="gear-label">选择灯光挡位</label>
            <select class="gear-select" id="gearSelect">
                <option value="1">1挡（低亮度）</option>
                <option value="2">2挡（中亮度）</option>
                <option value="3">3挡（高亮度）</option>
            </select>
        </div>

        <button class="action-btn" onclick="sendRequest()">执行控制</button>

        <!-- 新增开关按钮 -->
        <div class="switch-container">
            <button class="state-btn turn-on-btn" onclick="toggleState(0)">
                <i class="fas fa-power-off"></i> 开灯
            </button>
            <button class="state-btn turn-off-btn" onclick="toggleState(1)">
                <i class="fas fa-power-off"></i> 关灯
            </button>
        </div>
    </div>

    <div class="sensor-display">
        <div class="sensor-item">
            <span class="sensor-label">当前光照：</span>
            <span class="sensor-value" id="lightValue">0%</span>
        </div>
        <div class="sensor-item">
            <span class="sensor-label">当前挡位：</span>
            <span class="sensor-value" id="gearValue">0</span>
        </div>
    </div>
</div>

<div class="feedback-toast" id="feedbackToast"></div>

<script>
    const manualBtn = document.querySelector('[data-mode="manual_mode"]');
    const autoBtn = document.querySelector('[data-mode="auto_mode"]');
    const gearGroup = document.getElementById('gearGroup');
    const feedbackToast = document.getElementById('feedbackToast');
    let currentMode = 'manual_mode';
    let sensorInterval = null; // 传感器数据获取定时器

    // 模式切换逻辑
    document.querySelectorAll('.mode-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            currentMode = btn.dataset.mode;

            if (currentMode === 'auto_mode') {
                gearGroup.style.display = 'none';
            } else {
                gearGroup.style.display = 'block';
            }
        });
    });

    // 新增：开关灯控制函数
    async function toggleState(state) {
        try {
            const response = await fetch(`http://localhost:8083/api/v1/control/light/modify/state?state=${state}`, {
                method: 'GET',
            });
            const data = await response.json();

            if (response.ok) {
                showFeedback(data.msg || '状态切换成功', 'success');
                // 触发传感器数据更新（可选）
                fetchSensorData();
            } else {
                showFeedback(data.msg || '状态切换失败', 'error');
            }
        } catch (error) {
            showFeedback('网络请求失败，请检查连接', 'error');
            console.error('开关灯请求失败:', error);
        }
    }

    // 传感器数据获取函数
    async function fetchSensorData() {
        try {
            const response = await fetch('http://localhost:8083/api/v1/control/light/sensor/data');
            const data = await response.json();

            if (response.ok && data.code === 1) {
                document.getElementById('lightValue').textContent = `${data.data.light}%`;
                document.getElementById('gearValue').textContent = data.data.gear;
            } else {
                console.error('传感器数据获取失败:', data.msg || '未知错误');
            }
        } catch (error) {
            console.error('传感器数据请求失败:', error);
        }
    }

    async function sendRequest() {
        const gearSelect = document.getElementById('gearSelect');
        let gear = null;

        if (currentMode === 'manual_mode') {
            gear = gearSelect.value;
            if (!gear) {
                showFeedback('请选择手动挡位', 'error');
                return;
            }
        }

        const requestData = {
            modelName: currentMode,
            gear: currentMode === 'manual_mode' ? parseInt(gear) : 0
        };

        try {
            const response = await fetch('http://localhost:8083/api/v1/control/light/operation/light', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            });

            const data = await response.json();

            if (response.ok) {
                showFeedback(data.data || '操作成功', 'success');
            } else {
                showFeedback(data.msg || '操作失败', 'error');
            }
        } catch (error) {
            showFeedback('网络请求失败，请检查连接', 'error');
            console.error('请求错误：', error);
        }
    }

    function showFeedback(message, type) {
        const toastClass = type === 'success' ? 'success-toast' : 'error-toast';
        feedbackToast.className = `feedback-toast ${toastClass}`;
        feedbackToast.textContent = message;
        feedbackToast.classList.add('show');

        setTimeout(() => {
            feedbackToast.classList.remove('show');
            setTimeout(() => {
                feedbackToast.textContent = '';
            }, 300);
        }, 3000);
    }

    // 初始化设置
    gearGroup.style.display = 'block';
    window.addEventListener('load', () => {
        sensorInterval = setInterval(fetchSensorData, 5000); // 5秒更新一次
        fetchSensorData();
    });
    window.addEventListener('beforeunload', () => clearInterval(sensorInterval));
</script>
</body>
</html>